package cn.javass.xgen.genconf.confmanager;

import cn.javass.xgen.genconf.implementors.GenConfImplementor;
import cn.javass.xgen.genconf.implementors.ModuleGenConfImplementor;
import cn.javass.xgen.genconf.vo.GenConfModel;
import cn.javass.xgen.genconf.vo.ModuleConfModel;
import cn.javass.xgen.genconf.vo.NeedGenModel;

import java.util.HashMap;
import java.util.Map;

/**
 * 读取配置数据
 * 缓存配置数据
 */
public class ConfManager {

    //单例
    private static ConfManager confManager = null;

    private ConfManager(GenConfImplementor provider) {
        readConf(provider);
    }

    ;

    public static ConfManager getInstance(GenConfImplementor provider) {
        if (confManager == null) {
            return new ConfManager(provider);
        }
        return confManager;
    }

    //定义需要缓存的数据
    private GenConfModel genConf = new GenConfModel();

    private Map<String, ModuleConfModel> mapModuleConf = new HashMap<String, ModuleConfModel>();

    public GenConfModel getGenConf() {
        return genConf;
    }

    public Map<String, ModuleConfModel> getMapModuleConf() {
        return mapModuleConf;
    }

    private void readConf(GenConfImplementor provider) {
        //这里去真正的获取数据
        readGenConf(provider);
        for (NeedGenModel ngm : genConf.getNeedGen()){
            readOneModuleGenConf(ngm);
        }


    }

    private void readOneModuleGenConf(NeedGenModel ngm) {
        ModuleConfModel mcm = new ModuleConfModel();


        String providerClassName = this.genConf.getThemeById(ngm.getTheme()).getMapProviders().get(ngm.getProvider());
        //反射
        ModuleGenConfImplementor userGenConfImpl = null;
        try {
            userGenConfImpl = (ModuleGenConfImplementor) Class.forName(providerClassName).newInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }

        mcm = userGenConfImpl.getBaseModuleConfModel(ngm.getMapParams());
        mcm.setUseTheme(ngm.getTheme());
        mcm.setMapNeedGenTypes(userGenConfImpl.getMapNeedGenTypes(ngm.getMapParams()));
        mcm.setMapExtends(userGenConfImpl.getMapExtends(ngm.getMapParams()));

        //设置缓存
        mapModuleConf.put(mcm.getModelId(),mcm);
    }

    private void readGenConf(GenConfImplementor provider) {
        //把获取到的配置数据设置到属性上，并缓存下来
        genConf.setNeedGen(provider.getNeedGens());
        genConf.setThemes(provider.getThemes());
        genConf.setMapConstants(provider.getMapConstants());

    }


}
